package com.heima.bos.web.action.impl;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.heima.bos.domain.User;
import com.heima.bos.service.BaseService;
import com.heima.bos.service.UserService;
import com.heima.bos.utils.BOSUtils;
import com.heima.bos.utils.MD5Utils;
import com.heima.bos.web.action.UserActionInter;
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> implements UserActionInter {
	@Resource
	private UserService userService;
	private String checkcode;//验证码
	//属性注入角色的id
	private String[] roleIds;
	//当前用户名 属性注入
	private String accountName;
	
	/**
	 * 查询用户所有
	 */
	public String list(){
		List<User> list = userService.findAll();
		String[] excludes = new String[]{"password","roles","noticebills","remark"};
		writeList2Json(list, excludes);
		return NONE;
	}
	
	/**
	 * 添加用户 表单传递过来的还有角色的ids
	 */
	public String save(){
		String password = MD5Utils.md5(entity.getPassword());
		entity.setPassword(password);
		userService.save(entity,roleIds);
		return "addSuccess";
	}
	/**
	 * 根据用户名查找是否存在用户
	 */
	public void findUserByUsername(){
		try {
			List<User> list = userService.findByNameQuery("findUserByUsername", accountName);
			if(list != null && list.size()>0){
				ServletActionContext.getResponse().getWriter().print("1");
			}else{
				ServletActionContext.getResponse().getWriter().print("0");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 用户登录
	 */
	public String login(){
		if(BOSUtils.checkCode(checkcode)){
			Subject subject = SecurityUtils.getSubject();
			//获取当前用户信息（未认证
			String username = entity.getUsername();
			String password = MD5Utils.md5(entity.getPassword());
			//生成令牌
			AuthenticationToken token = new UsernamePasswordToken(username, password);
			try{
				//使用当前令牌尝试登录
				subject.login(token);//调用安全管理器，安全管理器再调用bos——realm
				//获取当前用户对象
				User user = (User) subject.getPrincipal();
				//放到域对象中
				BOSUtils.getSession().setAttribute("user", user);
			}catch(IncorrectCredentialsException e){
				this.addActionError(this.getText("passwordIncorrect"));
				e.printStackTrace();
				return "login";
			}catch (UnknownAccountException e) {
				this.addActionError(this.getText("usernameNotFound"));
				e.printStackTrace();
				return "login";
			}
			return "loginSuccess";
		}else{
			this.addActionError(this.getText("checkcodeFailed"));
			return "login";
		}
	}
	/**
	 * 用户登录(备份
	 */
	public String login_bak(){
		if(BOSUtils.checkCode(checkcode)){
			List<User> list = userService.findByNameQuery("findByUsernameAndPassword", entity.getUsername(),MD5Utils.md5(entity.getPassword()));
			if(list != null && list.size()>0){
				entity = list.get(0);
			}else{
				entity = null;
			}
			if(entity != null){
				BOSUtils.getSession().setAttribute("user", entity);
				return "loginSuccess";
			}else{
				this.addActionError(this.getText("loginFailed"));
			}
		}else{
			this.addActionError(this.getText("checkcodeFailed"));
		}
		return "login";
	}
	//退出
	public String logout(){
		//销毁session
		BOSUtils.getSession().invalidate();
		return "login";
	}
	//修改密码
	public String editPassword(){
		try {
			String password = ServletActionContext.getRequest().getParameter("password");
			User user = (User) BOSUtils.getSession().getAttribute("user");
			user.setPassword(MD5Utils.md5(password));
			userService.executeNameQuery("editPassword", MD5Utils.md5(password),user.getId());
			BOSUtils.getSession().setAttribute("user", user);
			ServletActionContext.getResponse().getWriter().write("1");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	@Override
	protected BaseService<User> getService() {
		return userService;
	}
	public void setAccountName(String accountName) {
		this.accountName = accountName;
	}
	//属性注入验证码
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
}
